//
// Created by xu on 2024/11/14.
//
#include <stdio.h>
#include <stdbool.h>
#include <SDL.h>
#include <SDL_image.h>

SDL_Window *gWindow = NULL;
SDL_Renderer *gRenderer = NULL;
SDL_Texture *gTexture = NULL;


bool init() {
    bool success = true;

    if (SDL_Init(SDL_INIT_VIDEO) != 0) {
        printf("SDL init failed! Error: %s\n", SDL_GetError());
        success = false;
    }

    gWindow = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480,
                               SDL_WINDOW_SHOWN);
    if (gWindow == NULL) {
        printf("Window could not be created! Error: %s\n", SDL_GetError());
        success = false;
    } else {
        gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED);
        if (gRenderer == NULL) {
            printf("Renderer could not be created! Error: %s\n", SDL_GetError());
            success = false;
        } else {
            SDL_SetRenderDrawColor(gRenderer, 0xff, 0xff, 0xff, 0xff);
            int imgFlags = IMG_INIT_PNG;
            if (!(IMG_Init(imgFlags) & imgFlags)) {
                printf("SDL_image init failed! Error: %s\n", IMG_GetError());
                success = false;
            }
        }
    }

    return success;
}

SDL_Texture *loadTexture(const char *input_file) {
    SDL_Texture *newTexture = NULL;
    SDL_Surface *loadedSurface = IMG_Load(input_file);
    if (loadedSurface == NULL) {
        printf("Unable to load image %s! Error: %s\n", input_file, IMG_GetError());
    } else {
        newTexture = SDL_CreateTextureFromSurface(gRenderer, loadedSurface);
        if (newTexture == NULL) {
            printf("Unable to create texture from %s! Error: %s\n", input_file, SDL_GetError());
        }
        SDL_FreeSurface(loadedSurface);
    }
    return newTexture;
}

bool loadMedia() {
    bool success = true;
    gTexture = loadTexture("qiuqiu.png");
    if (gTexture == NULL) {
        printf("Failed to load texture image!\n");
        success = false;
    }
    return success;
}

void close() {
    SDL_DestroyTexture(gTexture);
    gTexture = NULL;

    SDL_DestroyRenderer(gRenderer);
    gRenderer = NULL;

    SDL_DestroyWindow(gWindow);
    gWindow = NULL;

    IMG_Quit();
    SDL_Quit();
}


int main(int argc, char *argv[]) {
    if (!init()) {
        goto exit;
    }

    if (!loadMedia()) {
        goto exit;
    }

    bool quit = false;
    SDL_Event e;
    while (!quit) {
        while (SDL_PollEvent(&e) != 0) {
            if (e.type == SDL_QUIT) {
                quit = true;
            }
        }
        SDL_RenderClear(gRenderer);
        SDL_RenderCopy(gRenderer, gTexture, NULL, NULL);
        SDL_RenderPresent(gRenderer);
    }

    exit:
    close();
    return 0;
}